package com.CmJava.crowd.controller;



import com.CmJava.crowd.entity.CrowdException;
import com.CmJava.crowd.entity.Admin;
import com.CmJava.crowd.entity.ResultEntity;
import com.CmJava.crowd.service.AdminService;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;


import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.Enumeration;
import java.util.Set;


@Controller
public class AdminController {

    @Autowired
    private AdminService adminService;

    @Autowired
    private RedisTemplate redisTemplate;

    private int pageNum=20;

    // 管理员登陆
    @RequestMapping("adminLogin")
    @ResponseBody
    public ResultEntity adminLogin(@RequestParam("adminAccount") String adminAccount,
                             @RequestParam("adminPassword") String adminPassword,
                             HttpSession session){
        System.out.println(adminAccount+adminPassword);
        if (adminAccount==null || adminAccount.length()==0 ||
                adminPassword==null || adminPassword.length()==0){
            throw new CrowdException(CrowdException.EMPTY_EXCEPTION);
        }
        Admin admin = adminService.findAdmin(adminAccount,adminPassword);
        // admin登陆成功
        session.setAttribute("admin",admin);
        ResultEntity<Object> result = ResultEntity.successWithoutData();


        // 计算访客数
        new Thread(new Runnable() {
            @Override
            public void run() {
                String today = new SimpleDateFormat("yyyy-MM-dd").format(new Date());
                if(redisTemplate.opsForHash().hasKey("visitorNum",today)) {
                    int visitorNum = (int) redisTemplate.opsForHash().get("visitorNum", today);
                    redisTemplate.opsForHash().put("visitorNum", today, ++visitorNum);
                }else {
                    redisTemplate.opsForHash().put("visitorNum", today, 1);
                }
            }
        }).run();

        // 返回登陆后的结果
        return result;
    }

    //管理员退出登录,同pc下，只有不同浏览器是不同session
    @RequestMapping("adminOut")
    public String adminOut(HttpServletRequest request){
        Enumeration attributeNames = request.getSession().getAttributeNames();
        if(request.getSession().getAttribute("admin")!=null){
            while (attributeNames.hasMoreElements()){
                String attribute = attributeNames.nextElement().toString();
                request.getSession().removeAttribute(attribute);
            }
        }
        return "redirect:/login.html";
    }

    // index.html 通过ajax获取登陆的管理员姓名
    @RequestMapping("adminName")
    @ResponseBody
    public ResultEntity adminName(HttpSession session){
        Admin admin = (Admin) session.getAttribute("admin");
        ResultEntity<Admin> adminresultEntity = ResultEntity.successWithData(admin);
        return adminresultEntity;
    }

    //获取管理员列表
    @RequestMapping("adminList")
    @ResponseBody
    public PageInfo adminList(@RequestParam(value = "currentPage" ) String currentPage,
                              @RequestParam(value = "keyWord") String keyWord){
        int cp = Integer.parseInt(currentPage);
        PageInfo<Admin> adminPageInfo=adminService.adminList(cp,pageNum,keyWord);
        return adminPageInfo;
    }

    //批量删除管理员
    @RequestMapping("deleteAdminByList")
    @ResponseBody
    public ResultEntity deleteAdminByList(@RequestParam("pkArray") String pkArray){
        String[] split = pkArray.split(",");
        ArrayList<String> primaryKeyList = new ArrayList<>();
        for (String s : split) {
            primaryKeyList.add(s);
        }
        ResultEntity resultEntity = adminService.deleteAdminByList(primaryKeyList);
        return resultEntity;
    }


    //删除单个管理员
    @RequestMapping("deleteOneAdmin")
    @ResponseBody
    public ResultEntity deleteOneAdmin(@RequestParam("primaryKey") String primaryKey){

        ResultEntity resultEntity = adminService.deleteOneAdmin(primaryKey);
        return resultEntity;
    }

    // 获取单个管理员信息
    @RequestMapping("findOneAdmin")
    @ResponseBody
    public ResultEntity findOneAdmin(@RequestParam("primaryKey") String primaryKey){
        ResultEntity resultEntity = adminService.findOneAdmin(primaryKey);
        return resultEntity;
    }

    // 更新单个管理员信息
    @RequestMapping("updateOneAdmin")
    @ResponseBody
    public ResultEntity updateOneAdmin(@RequestParam("primaryKey") String primaryKey,
                                       @RequestParam("adminAccount") String adminAccount,
                                       @RequestParam("adminPassword") String adminPassword,
                                       @RequestParam("adminName") String adminName,
                                       @RequestParam("email") String email){
        Admin admin = new Admin(Integer.parseInt(primaryKey), adminAccount, adminPassword, adminName, email, null);
        ResultEntity resultEntity = adminService.updateOneAdmin(admin);
        return resultEntity;
    }

    // 注册管理员
    @RequestMapping("adminRegister")
    @ResponseBody
    public ResultEntity register(@RequestParam("adminAccount") String adminAccount,
                                       @RequestParam("adminPassword") String adminPassword,
                                       @RequestParam("adminName") String adminName,
                                       @RequestParam("adminEmail") String email,
                                        HttpSession session){
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String creatDate = simpleDateFormat.format(new Date());
        Admin admin = new Admin(null, adminAccount, adminPassword, adminName, email, creatDate);
        try {
            adminService.addAdmin(admin);
        }catch (Exception e){
            return ResultEntity.failWithoutMessage();
        }
        ResultEntity resultEntity = adminLogin(adminAccount, adminPassword, session);
        return resultEntity;
    }

    // 忘记密码
    @RequestMapping("adminForgotPassword")
    @ResponseBody
    public ResultEntity forgotPassword(@RequestParam("adminAccount") String adminAccount,
                                 @RequestParam("adminEmail") String email,
                                 HttpSession session){
        ResultEntity resultEntity1;
        ResultEntity resultEntity = adminService.forgotPassword(adminAccount,email);
        if (resultEntity.getResultFlag()==true){
            Admin admin = (Admin) resultEntity.getData();
            resultEntity1 = adminService.updateOneAdmin(admin);
            return resultEntity1;
        }else {
            return ResultEntity.failWithoutMessage();
        }
    }

    // 累计访客数
    @RequestMapping("totalVisotor")
    @ResponseBody
    public ResultEntity totalVisotor(){
        Set visitDate = redisTemplate.opsForHash().keys("visitorNum");
        int sum=0;
        for (Object date : visitDate) {
            sum += (int) redisTemplate.opsForHash().get("visitorNum", (String) date);
        }
        return ResultEntity.successWithData(sum);
    }

    // 今日访客数
    @RequestMapping("todayVisotor")
    @ResponseBody
    public ResultEntity todayVisotor(){
        String today = new SimpleDateFormat("yyyy-MM-dd").format(new Date());
        int num= (int) redisTemplate.opsForHash().get("visitorNum", today);
        return ResultEntity.successWithData(num);
    }



    //测试的，以后删掉
    @RequestMapping("adminList1")
    @ResponseBody
    public PageInfo adminList1(){
        PageInfo<Admin> adminPageInfo=adminService.adminList(1,2,"om");
        return adminPageInfo;
    }

}
